package jt.classic.app.addressbook;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jt.classic.app.clgl.jsy.JsyManager;
import jt.classic.app.util.Recursion;
import jt.classic.app.util.TreeNode;
import jt.classic.system.ISystem;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.user.IUser;
import jt.classic.system.wordbook.WordBookUtil;
import net.sf.json.JSONObject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.limp.basework.SimpleBean;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.tools.BaseworkUtil;
import org.limp.mine.Controller;
import org.limp.mine.DataTrimmer;
import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;
import org.limp.mine.XMLTool;
public class AddressBookAction extends DispatchAction {

    

    /**
     * 获取个人通讯录列表
     * @param mapping
     * @param form
     * @param request 所在节点id
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward getPerAddressList(ActionMapping mapping,
        ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        response.setContentType("text/xml;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");

        IUser user = ISystem.getSessionUser(request);
         String userId = (String) user.id();

        //String userId = "0001";
        String nodeid = request.getParameter("id");
        String posStart = request.getParameter("posStart");
        Connection conn = null;
        Map resultMap = new HashMap();
        List resultList = new ArrayList();
        SystemDataSource ds = SystemDataSource.getInstance();

        if ((nodeid == null) || nodeid.equalsIgnoreCase("")) {
            return null;
        }

        try {
            conn = ds.getConnection();

            AddressBookManager abManager = new AddressBookManager(conn);
            // 根据上一级节点,查询该节点下的所有节点
            resultList = abManager.getPerList(userId, nodeid);

            resultMap.put("rows", resultList);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        JSONObject resultJsonObject = JSONObject.fromObject(resultMap);
        request.setAttribute("result", resultJsonObject.toString());

        return mapping.findForward("result");
    }

    /**
     * 获取个人通讯录类别树
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return 
     * @throws Exception
     */
    public ActionForward personAddressBookTree(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        response.setContentType("text/xml;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        ActionForward forward = null;
        IUser user = ISystem.getSessionUser(request);
        String userId = (String) user.id();
        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String nodeid = StringTool.checkString(param.get("node"));
        Connection conn = null;
        SystemDataSource ds = SystemDataSource.getInstance();

        try {
            conn = ds.getConnection();

            AddressBookManager abManager = new AddressBookManager(conn);

            // 根据上一级节点,查询该节点下的所有节点
            List<Map> list = abManager.getPerNodeList(userId);
            int defultCount = Integer.parseInt(WordBookUtil.getWordBookItemName(
                        "addressBook", "defultPerAddBookCatCount", "2"));
            List<TreeNode> nodeList = new ArrayList<TreeNode>();
            //添加默认分类
            if (defultCount > 0) {
                for (int i = 0; i < defultCount; i++) {
                    Map catMap = new HashMap();
                    catMap.put("ID", "-" + (i + 1));
                    catMap.put("CATNAME",
                        WordBookUtil.getWordBookItemName("addressBook",
                            "-" + (i + 1), ""));
                    list.add(catMap);
                }
            }
            
            
            
            for (Map info : list) {
                TreeNode node = new TreeNode();

                if (info != null) {
                    String pkid = (String) info.get("ID");
                    node.setId(pkid);

                    String text = (String) info.get("CATNAME");
                    node.setText(text);

                    String summary = (String) info.get("CATNAME");
                    node.setQtip(summary);
                    
                    node.setLeaf(true);
                                      
                    node.setParentId("-99");
                    nodeList.add(node);
                }
            }
            
            Recursion recursion = new Recursion();
            recursion.recursionFn(nodeList, new TreeNode(nodeid, "0", "0"));
            request.setAttribute("result",
                    recursion.modifyStr(recursion.getReturnStr().toString()));
            forward = mapping.findForward("result");
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }
        
        return forward;
    }

    /**
     * 添加个人通讯录类别
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return 
     * @throws Exception
     */
    public ActionForward addPersonAddrBookCatgory(ActionMapping mapping,
        ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        Connection conn = null;
        SystemDataSource ds = SystemDataSource.getInstance();
        IUser user = ISystem.getSessionUser(request);
         String userId = (String) user.id();

        try {
            CommonBean4HSQ cbh = new CommonBean4HSQ(request);
            Map params = cbh.getResource();

            String cname = (String) params.get("catname");

            conn = ds.getConnection();

            AddressBookManager abManager = new AddressBookManager(conn);

            // 根据上一级节点,查询该节点下的所有节点
            boolean result = abManager.addPersonAddrBookCatgory(cname, userId);
            conn.commit();

            request.setAttribute("result", "{success: "+result+"}");
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }
        
        return mapping.findForward("result");
    }

    /**
     * 保存个人通讯录分类
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return forward
     * @throws Exception
     */
    public ActionForward saveAddrBookCat(ActionMapping mapping,
        ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        ActionForward forward = null;
        
        CommonBean4HSQ cbh = new CommonBean4HSQ(request, "UTF-8");
        Map params = cbh.getResource();
        String cname = (String) params.get("catname");
        String cid = (String) params.get("catid");
        IUser user = ISystem.getSessionUser(request);
         String userId = (String) user.id();
        cbh.getResource().put("userId", userId);
        cbh.getResource().put("cname", cname);
        cbh.getResource().put("cid", cid);
        
        Connection conn = null;

        SystemDataSource ds = SystemDataSource.getInstance();

        try {
            conn = ds.getConnection();

            SimpleBean sb = BaseworkUtil.analyzerSimpleBean("APP_ADDRBOOK_CATEGORY",
                    cbh);

            BaseworkUtil util = new BaseworkUtil();
            util.manualUpdate("APP_ADDRBOOK_CATEGORY", sb, conn);
            conn.commit();
            request.setAttribute("result", "{success: true}");
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            conn.rollback();
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 保存个人通讯录分类
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return forward
     * @throws Exception
     */
    public ActionForward delAddrBookCat(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request, "UTF-8");
        Map params = cbh.getResource();
        IUser user = ISystem.getSessionUser(request);
         String userId = (String) user.id();
        Connection conn = null;

        SystemDataSource ds = SystemDataSource.getInstance();

        try {
            conn = ds.getConnection();

            AddressBookManager abManager = new AddressBookManager(conn);
            SimpleBean sb = BaseworkUtil.analyzerSimpleBean("APP_ADDRBOOK_CATEGORY",
                    cbh);

            BaseworkUtil util = new BaseworkUtil();
            util.manualDelete("APP_ADDRBOOK_CATEGORY", sb, conn);

            abManager.delPerAddrBookByCat((String) params.get("cid"), userId);
            conn.commit();
            request.setAttribute("result", "{success: true}");
            
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            conn.rollback();
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 通讯录保存
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return forward
     * @throws Exception
     */
    public ActionForward addAddrBook(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map params = cbh.getResource();

        String catid = StringTool.checkString(params.get("catid"));

        Connection conn = null;

        SystemDataSource ds = SystemDataSource.getInstance();

        try {
            conn = ds.getConnection();

            SimpleBean sb = BaseworkUtil.analyzerSimpleBean("APP_ADDRBOOK", cbh);

            BaseworkUtil util = new BaseworkUtil();
            util.manualSave("APP_ADDRBOOK", sb, conn);

            conn.commit();

            //String url = "/addressbook.do?method=query&catid=" + catid;

            request.setAttribute("result", "{success: true}");
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            conn.rollback();
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 通讯录保存(通过ajax方式提交)
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return forward
     * @throws Exception
     */
    public void addAddrBookAjax(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Connection conn = null;

        SystemDataSource ds = SystemDataSource.getInstance();

        try {
            conn = ds.getConnection();

            SimpleBean sb = BaseworkUtil.analyzerSimpleBean("APP_ADDRBOOK", cbh);

            BaseworkUtil util = new BaseworkUtil();
            util.manualSave("APP_ADDRBOOK", sb, conn);

            conn.commit();

            response.getWriter().write("success");
            response.getWriter().close();
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            conn.rollback();
        } finally {
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 通讯录编辑
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return forward
     * @throws Exception
     */
    public ActionForward editAddrBook(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String id = StringTool.checkString(request.getParameter("id"));

        Connection conn = null;

        SystemDataSource ds = SystemDataSource.getInstance();

        try {
            conn = ds.getConnection();

            String sql = "SELECT * FROM APP_ADDRBOOK WHERE ID = '" + id + "'";

            DataTrimmer trimmer = new DataTrimmer(conn);

            Map<String,String> info = trimmer.searchSingleData(sql);
            
            Map<String,String> m = new HashMap<String,String>(); 
            m.put("uname", info.get("NAME"));
            m.put("phone", info.get("OFFICEPHONE"));
            m.put("mobile", info.get("MOBILEPHONE"));
            m.put("address", info.get("ADDRESS"));
            m.put("catid", info.get("CATID"));
            m.put("id", info.get("ID"));
            m.put("fax", info.get("OFFICEFAX"));
            m.put("email", info.get("EMAIL"));
            request.setAttribute("result",
                    "{success: true, data:"+JSONObject.fromObject(m).toString()+"}");
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
    * 通讯录修改
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return forward
    * @throws Exception
    */
    public ActionForward updateAddrBook(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map params = cbh.getResource();

        String catid = StringTool.checkString(params.get("catid"));

        Connection conn = null;

        SystemDataSource ds = SystemDataSource.getInstance();

        try {
            conn = ds.getConnection();

            SimpleBean sb = BaseworkUtil.analyzerSimpleBean("APP_ADDRBOOK", cbh);

            BaseworkUtil util = new BaseworkUtil();
            util.manualUpdate("APP_ADDRBOOK", sb, conn);

            conn.commit();


            request.setAttribute("result", "{success: true}");
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            conn.rollback();
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 通讯录删除
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return forward
     * @throws Exception
     */
    public ActionForward deleteAddrBook(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map params = cbh.getResource();
        String catid = StringTool.checkString(params.get("catid"));
        String ids = StringTool.checkString(params.get("ids"));

        Connection conn = null;

        SystemDataSource ds = SystemDataSource.getInstance();

        try {
            conn = ds.getConnection();

            AddressBookManager manager = new AddressBookManager(conn);

            manager.deleteS(ids);

            conn.commit();
            String url = "/addressbook.do?method=query&catid=" + catid;
            forward = new ActionForward();
            forward.setPath(url);

            forward.setRedirect(true);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            conn.rollback();
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 查询操作
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public ActionForward query(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String qname = StringTool.checkString(param.get("qname"));
        String catid = StringTool.checkString(param.get("catid"));

        String pageNO = StringTool.checkString(param.get("pageNO"));
        String limit = StringTool.checkString(param.get("limit"));

        request.setAttribute("qname", qname);
        request.setAttribute("catid", catid);

        StringBuffer where = new StringBuffer(" WHERE 1=1 ");

        IUser user = ISystem.getSessionUser(request);

        where.append(" AND USERID = '" + (String) user.id() + "'");

        if (!qname.equals("")) {
            where.append(" AND NAME LIKE '%" + qname + "%'");
        }

        if (!catid.equals("")) {
            where.append(" AND CATID = '" + catid + "'");
        }

        String sql1 = "SELECT COUNT(ID) FROM APP_ADDRBOOK " + where.toString();
        String sql2 = "SELECT * FROM APP_ADDRBOOK " + where.toString() +
            " ORDER BY NAME DESC";

        String url = jt.classic.system.ISystem.getContextPath() +
            "/app/addressbook.do?method=query";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            Map catInfo = new HashMap();

            if ("-1".equals(catid)||"-2".equals(catid)) {
                catInfo.put("CATNAME",
                    WordBookUtil.getWordBookItemName("addressBook", catid, ""));
            } else {
                DataTrimmer trimmer = new DataTrimmer(conn);

                String sql = "SELECT CATNAME FROM APP_ADDRBOOK_CATEGORY WHERE ID = '" +
                    catid + "'";
                catInfo = trimmer.searchSingleData(sql);
            }

            request.setAttribute("cat", catInfo);

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, limit);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            Controller controller = plus.getController("form1");

            controller.setType("input");

            Label label = plus.getLabel();

            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            request.setAttribute("result", result);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("querylist");
    }

    /**
     * 查询操作
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public ActionForward select(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String qname = StringTool.checkString(param.get("qname"));
        String catid = StringTool.checkString(param.get("catid"));

        String pageNO = StringTool.checkString(param.get("pageNO"));
        String limit = "5";

        request.setAttribute("qname", qname);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmer trimmer = new DataTrimmer(conn);

            String sql = "SELECT ID, CATNAME FROM APP_ADDRBOOK_CATEGORY WHERE USERID = '" +
            (String) user.id() + "'";

            List catList = trimmer.searchMultiData(sql);

            int defultCount = Integer.parseInt(WordBookUtil.getWordBookItemName(
                        "addressBook", "defultPerAddBookCatCount", "2"));

            //添加默认分类
            if (defultCount > 0) {
                for (int i = 0; i < defultCount; i++) {
                    Map catMap = new HashMap();
                    catMap.put("ID", "-" + (i + 1));
                    catMap.put("CATNAME",
                        WordBookUtil.getWordBookItemName("addressBook",
                            "-" + (i + 1), ""));
                    catList.add(catMap);
                }
            }

            request.setAttribute("catList", catList);

            Map catInfo = null;

            if (catid.equals("")) {
                if ((catList != null) && !catList.isEmpty()) {
                    catInfo = (Map) catList.get(0);
                    catid = (String) catInfo.get("ID");
                } else {
                    catid = "0";
                }
            } else {
                sql = "SELECT CATNAME FROM APP_ADDRBOOK_CATEGORY WHERE ID = '" +
                    catid + "'";

                catInfo = trimmer.searchSingleData(sql);
            }

            request.setAttribute("cat", catInfo);

            request.setAttribute("catid", catid);

            StringBuffer where = new StringBuffer(" WHERE 1=1 ");

            where.append(" AND USERID = '" + (String) user.id() + "'");

            if (!qname.equals("")) {
                where.append(" AND NAME LIKE '%" + qname + "%'");
            }

            if (!catid.equals("")) {
                where.append(" AND CATID = '" + catid + "'");
            }

            String sql1 = "SELECT COUNT(ID) FROM APP_ADDRBOOK " +
                where.toString();
            String sql2 = "SELECT * FROM APP_ADDRBOOK " + where.toString() +
                " ORDER BY NAME DESC";

            String url = jt.classic.system.ISystem.getContextPath() +
                "/app/addressbook.do?method=select";

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, limit);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            Controller controller = plus.getController("form1");

            controller.setType("input");

            Label label = plus.getLabel();

            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            /*
             * ListRange lr = new ListRange();
             * lr.setTotalSize(label.totaldata()); lr.setList(resultList);
             * lr.setSuccess(true); outJson(lr, response);
             */
            request.setAttribute("result", result);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("selectlist");
    }
}
